﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Facade.Interface;
using Crosland.Automotriz.Facade.Facade;
using Crosland.Automotriz.Core;
using Crosland.Automotriz.Logic.Linq;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Configuration;
using Crosland.Automotriz.Logic.ControlExeption;



namespace Crosland.Automotriz.Web.Repuestos
{
    public partial class wFrmManualesPartesVehiculosSistemaModelo : System.Web.UI.Page
    {
        private iFacadeSistema facadeModelo = null;

        private string idNegocio = ConfigurationManager.AppSettings["Negocio"];

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack == false)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", "JavaScript:confirmSubmitResult();", true);
                this.ListaModeloActivos();
            }

        }

        private void ListaModeloActivos()
        {

            try
            {
                facadeModelo = new FacadeSistema();
                gvSisModelo.DataSource = facadeModelo.listar_filtro_modelo_s();
                gvSisModelo.DataBind();
            }
            catch (Exception ex)
            {
                GuardarExceptionLog(ex.Message, ex, "ListaModeloActivos");
                MensajesError(ex.Message, ex, "ListaModeloActivos");

            }




        }

        private void ListaModeloInactivos()
        {
            try
            {
                facadeModelo = new FacadeSistema();
                gvModelos.DataSource = facadeModelo.listar_filtro_modelo(txtModelo.Text, cboMarca.Text);
                gvModelos.DataBind();
            }
            catch (Exception ex)
            {
                GuardarExceptionLog(ex.Message, ex, "ListaModeloInactivos");
                MensajesError(ex.Message, ex, "ListaModeloInactivos");
            }


        }

        private void AgregaModelo()
        {

            try
            {
                facadeModelo = new FacadeSistema();
                List<Object> selectedItem = gvModelos.GetSelectedFieldValues("ID_MODELO");
                foreach (object item in selectedItem)
                {
                    facadeModelo.Actualizar_Estado_Modelo_S((Int32)item);
                }
                this.ListaModeloActivos();
            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "btnPopAgregar_Click");
                MensajesError(exc.Message, exc, "btnPopAgregar_Click");
            }
        }

        private void AnulaModelo()
        {

            try
            {
                facadeModelo = new FacadeSistema();
                int intIdmodelo = Convert.ToInt32(gvSisModelo.GetRowValues(gvSisModelo.FocusedRowIndex, "ID_MODELO"));
                bool resultado = facadeModelo.Actualizar_Estado_Modelo_N(intIdmodelo);

                if (resultado)
                {
                    lblmsj.Text = "Se anuló correctamente!.";
                    popupMsj.ShowOnPageLoad = true;
                    this.ListaModeloActivos();
                }
            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "btnPopAceptar_Click");
                MensajesError(exc.Message, exc, "btnPopAceptar_Click");
            }
        }

        protected void gvModelo_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            this.ListaModeloActivos();
        }

        protected void gvModelo_PageIndexChanged(object sender, EventArgs e)
        {
            this.ListaModeloActivos();
        }

        protected void btnPopAgregar_Click(object sender, EventArgs e)
        {
            this.AgregaModelo();
        }

        protected void btnPopupBuscar_Click(object sender, EventArgs e)
        {
            this.ListaModeloInactivos();
        }

        protected void gvSisModelo_FocusedRowChanged(object sender, EventArgs e)
        {


            try
            {
                Timer1.Enabled = true;
                UploadCargaManual.Enabled = true;
                int intIndex = gvSisModelo.FocusedRowIndex;
                lblDescripcion.Text = gvSisModelo.GetRowValues(intIndex, "DES_MODELO").ToString();
                lblMarca.Text = gvSisModelo.GetRowValues(intIndex, "DES_MARCA").ToString();
                lblNumeroRueda.Text = gvSisModelo.GetRowValues(intIndex, "DES_NUM_RUEDA").ToString();

                facadeModelo = new FacadeSistema();
                int id_modelo = Convert.ToInt32(gvSisModelo.GetRowValues(intIndex, "ID_MODELO"));
                gvListarImgenes.DataSource = facadeModelo.ListarT_Man_filtro(id_modelo);
                gvListarImgenes.DataBind();
                string row1 = (gvListarImgenes.GetRowValues(0, "DES_IMAGEN")).ToString();
                Image.ImageUrl = ConfigurationManager.AppSettings["RutaFotoModelo"] + "/" + Convert.ToString(row1);

            }
            catch
            {
                Image.ImageUrl = ConfigurationManager.AppSettings["RutaFotoModelo"] + "/";

            }
        }

        private static int i = 1;

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (i >= gvListarImgenes.VisibleRowCount)
                {
                    i = 0;
                }
                string row1 = (gvListarImgenes.GetRowValues(i, "DES_IMAGEN")).ToString();
                Image.ImageUrl = ConfigurationManager.AppSettings["RutaFotoModelo"] + "/" + Convert.ToString(row1);
                i++;
            }
            catch
            {
                Image.ImageUrl = ConfigurationManager.AppSettings["RutaFotoModelo"] + "/";

            }
        }

        protected void gvModelos_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            this.ListaModeloInactivos();
        }

        protected void gvModelos_PageIndexChanged(object sender, EventArgs e)
        {
            this.ListaModeloInactivos();
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Repuestos/wFrmManualesPartesVehiculosSistemas.aspx?id=" + idNegocio);
        }

        protected void btnPopAceptar_Click(object sender, EventArgs e)
        {
            this.AnulaModelo();

        }

        protected void btnModificar_Click(object sender, EventArgs e)
        {

            try
            {
                if (gvSisModelo.FocusedRowIndex == -1)
                {

                    return;
                }
                else
                {
                    Session["id_modelo"] = Convert.ToInt32(gvSisModelo.GetRowValues(gvSisModelo.FocusedRowIndex, "ID_MODELO"));
                    Response.Redirect("~/Repuestos/wFrmManualesPartesVehiculosSistemaModeloActualizar.aspx?id=" + idNegocio);
                }

            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "btnModificar_Click");
                MensajesError(exc.Message, exc, "btnModificar_Click");
            }



        }

        private void CargaManual()
        {

            try
            {
                if (UploadCargaManual.FileContent.Length == 0)
                {
                    lblmsj.Text = "Seleccione un archivo .pdf";
                    popupMsj.ShowOnPageLoad = true;
                    return;
                }

                int intIndex = gvSisModelo.FocusedRowIndex;
                int intIdModelo = Convert.ToInt32(gvSisModelo.GetRowValues(intIndex, "ID_MODELO"));
                string strDesModelo = Convert.ToString(gvSisModelo.GetRowValues(intIndex, "DES_MODELO"));
                string ruta = Server.MapPath("~/" + ConfigurationManager.AppSettings["RutaManual"]);
                if (!Directory.Exists(ruta))
                    Directory.CreateDirectory(ruta);
                UploadCargaManual.SaveAs(ruta + "/" + strDesModelo + "_" + intIdModelo + ".pdf");
                clsTd_ModeloLogic clst_modelologic = new clsTd_ModeloLogic();
                string strDesManual = strDesModelo + "_" + intIdModelo + ".pdf";
                bool resultado = clst_modelologic.Actualizar_Manual(strDesManual, intIdModelo);
                if (resultado)
                {
                    this.ListaModeloActivos();
                    lblmsj.Text = "Se agregó correctamente";
                    popupMsj.ShowOnPageLoad = true;
                }
            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "CargaManual");
                MensajesError(exc.Message, exc, "CargaManual");
            }

        }

        private void DescargaManuales()
        {


            try
            {
                int intIndex = gvSisModelo.FocusedRowIndex;
                int id_modelo = Convert.ToInt32(gvSisModelo.GetRowValues(intIndex, "ID_MODELO"));
                string des_modelo = Convert.ToString(gvSisModelo.GetRowValues(intIndex, "DES_MODELO"));
                string filepath = ConfigurationManager.AppSettings["RutaManual"] + "\\";
                string filename = des_modelo + "_" + id_modelo + ".pdf";
                string path = Server.MapPath(filepath + filename);
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.Flush();
                Response.WriteFile(path);
                Response.End();
            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "descargarManuales");
                MensajesError(exc.Message, exc, "descargarManuales");
            }

        }

        protected void UploadCargaManual_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            try
            {
                int intIndex = gvSisModelo.FocusedRowIndex;
                int intIdModelo = Convert.ToInt32(gvSisModelo.GetRowValues(intIndex, "ID_MODELO"));
                string strDesModelo = Convert.ToString(gvSisModelo.GetRowValues(intIndex, "DES_MODELO"));
                if (e.IsValid)
                {
                    string strFilePath = Server.MapPath("~/" + ConfigurationManager.AppSettings["RutaManual"] + "/" + strDesModelo + "_" + intIdModelo + ".pdf");
                    e.UploadedFile.SaveAs(strFilePath);
                }
            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "UploadCargaManual_FileUploadComplete");
                MensajesError(exc.Message, exc, "UploadCargaManual_FileUploadComplete");
            }
        }

        protected void btnDescargarManaual_Click(object sender, EventArgs e)
        {
            try
            {

                int intIndex = gvSisModelo.FocusedRowIndex;
                if (intIndex == -1)
                {
                    lblmsj.Text = "Seleccione un registro";
                    popupMsj.ShowOnPageLoad = true;
                    return;
                }

                int intIdmodelo = Convert.ToInt32(gvSisModelo.GetRowValues(intIndex, "ID_MODELO"));
                string strDesModelo = gvSisModelo.GetRowValues(intIndex, "DES_MODELO").ToString();
                string strArchivo = Server.MapPath("~/" + ConfigurationManager.AppSettings["RutaManual"] + "/" + strDesModelo + "_" + intIdmodelo + ".pdf");
                if (File.Exists(strArchivo))
                {
                    this.DescargaManuales();
                }
                else
                {
                    lblmsj.Text = "El archivo no existe.";
                    popupMsj.ShowOnPageLoad = true;
                }

            }
            catch (Exception exc)
            {
                GuardarExceptionLog(exc.Message, exc, "btnDescargarManaual_Click");
                MensajesError(exc.Message, exc, "btnDescargarManaual_Click");
            }
        }

        protected void btnAgregar_Click(object sender, EventArgs e)
        {
            Timer1.Enabled = false;

        }

        private void GuardarExceptionLog(String msgUsu, Exception ex, String metError)
        {
            try
            {
                String msgReal, fhError, pagError, codUsu;
                msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
                codUsu = Session["User"].ToString();
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                int number = 0;
                for (int i = 0; i < trace.FrameCount; i++)
                {
                    System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                    number = sf.GetFileLineNumber();
                }
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                new Logg().ErrorLog(Server.MapPath("~/Logs/ErrorLog.csv"), msgUsu, msgReal, pagError, metError, codUsu, number);
            }
            catch (DataException e) { MensajesError(e.Message, e, "GuardarExceptionLog"); }
            catch (RunException re) { MensajesError(re.Message, re, "GuardarExceptionLog"); }

        }

        private void MensajesError(String msgUsu, Exception ex, String metError)
        {
            Crosland.Automotriz.Web.UserControl.MensajeError uc = (Crosland.Automotriz.Web.UserControl.MensajeError)Master.FindControl("ucErrorMensaje");
            String msgReal, fhError, pagError, codUsu;
            msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
            pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
            codUsu = Session["User"].ToString();
            fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
            int number = 0;
            for (int i = 0; i < trace.FrameCount; i++)
            {
                System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                number = sf.GetFileLineNumber();
            }
            uc.Errores(msgUsu, msgReal, fhError, pagError, metError, codUsu, number);
        }

     
        protected void btnAgregarManual_Click(object sender, EventArgs e)
        {
            this.CargaManual();

        }

    }
}